package com.xincheng.shuimalong.activity.mydetail.wallet;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.util.UIUtil;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.SucceedActivity;
import com.xincheng.shuimalong.activity.bank.MyBankCardActivity;
import com.xincheng.shuimalong.activity.mydetail.setting.BindPhoneActivity;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.bank.BankCard;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.view.PasswordView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * Created by xiaote on 2017/7/24.
 */

public class WithdrawDepositActivity extends BaseActivity {
    @BindView(R.id.bankcard_bind_layout)
    RelativeLayout mBankcardBindLayout;
    @BindView(R.id.bankcard_name_tv)
    TextView mBankcardNameTv;
    @BindView(R.id.bankcard_no_last_tv)
    TextView mBankcardNoLastTv;
    @BindView(R.id.withdraw_deposit_money_et)
    EditText mMoneyEt;
    @BindView(R.id.money_least_tv)
    TextView mMoneyLeastTv;

    private BankCard.Data mBankCardData;
    private String mToken;
    private String mTotalMoney = "0";

    private AlertView mMessageAlert;
    private AlertView mPassworAlert;
    private TextView[] mPwdTvList;
    private PasswordView mPasswordView;

    private String mPayPwd;
    private String mMoney;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_withdraw_deposit;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.withdraw_deposit));
        setRightTv(getString(R.string.add));
        mRightTv.setTextColor(ContextCompat.getColor(this, R.color.black_33));
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            mTotalMoney = extras.getString(IntentKey.TOTAL_MONEY, "0");
        }
        mMoneyLeastTv.setText(getString(R.string.money_least, mTotalMoney));
        getBankCard();
    }

    private void initMsgAlert() {
        mMessageAlert = new AlertView(this, null, "尚未设置交易密码，是否设置交易密码", getString(R.string.cancel),
                new String[]{getString(R.string.confirm)}, null, AlertView.Style.Alert, new
                OnAlertItemClickListener() {
                    @Override
                    public void onItemClick(AlertView alertView, int position) {
                        switch (position) {
                            case 0:
                                Bundle extras = new Bundle();
                                extras.putBoolean(IntentKey.MODIFY_FOR_PAYPWD, true);
                                ShowActivity.showActivity(getContext(), BindPhoneActivity.class, extras);
                                break;
                        }
                    }
                });
    }

    private void initPasswordAlert() {
        mPassworAlert = new AlertView(this, AlertView.Style.Alert);
        View view = LayoutInflater.from(this).inflate(R.layout.withdraw_desposit_dialog, null);
        TextView titleTv = UIUtil.findViewById(view, R.id.password_title_tv);
        titleTv.setText(getString(R.string.withdraw_deposit));
        mPwdTvList = new TextView[6];
        mPwdTvList[0] = UIUtil.findViewById(view, R.id.tv_pass1);
        mPwdTvList[1] = UIUtil.findViewById(view, R.id.tv_pass2);
        mPwdTvList[2] = UIUtil.findViewById(view, R.id.tv_pass3);
        mPwdTvList[3] = UIUtil.findViewById(view, R.id.tv_pass4);
        mPwdTvList[4] = UIUtil.findViewById(view, R.id.tv_pass5);
        mPwdTvList[5] = UIUtil.findViewById(view, R.id.tv_pass6);
        mPasswordView = UIUtil.findViewById(view, R.id.password_view);
        mPasswordView.setTvList(mPwdTvList);
        mPasswordView.setOnFinishInput(new PasswordView.OnPasswordInputCallback() {
            @Override
            public void inputFinish() {
                mPayPwd = mPasswordView.getStrPassword();
                mPassworAlert.dismiss();
                submitWithdrawDeposit();
            }
        });
        mPassworAlert.addExtView(view);
    }

    private void submitWithdrawDeposit() {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.APPLY_WITHDRAW,
                PostParam.applyWithdraw(mToken, mMoney, mBankCardData.getId(), mPayPwd),
                new BaseObserver(getContext(), getString(R.string.loading_submit)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        showToast(msg);
                        double totalMoney = Double.parseDouble(mTotalMoney);
                        double despositMoney = Double.parseDouble(mMoney);
                        mMoneyEt.setText("");
                        mTotalMoney = CommonUtil.getMoneyStr(totalMoney - despositMoney);
                        mMoneyLeastTv.setText(getString(R.string.money_least, mTotalMoney));

                        Constant.SUCCESS = true;
                        Bundle extras = new Bundle();
                        extras.putInt(IntentKey.FROM, 3);
                        extras.putString(IntentKey.TITLE_MESSAGE, getString(R.string.deposit_success));
                        extras.putString(IntentKey.SUCCESS_MESSAGE,
                                getString(R.string.deposit_success_message));
                        ShowActivity.showActivityForResult(getContext(), SucceedActivity.class, extras,
                                RequestCodeKey.GO_DESPOSE);
                    }
                });
    }

    @OnClick(R.id.withdraw_deposit_confirm_tv)
    public void withdrawDepositConfirm() {
        if (checkData()) {
            mMoney = mMoneyEt.getText().toString().trim();
            boolean isSetPayPwd = PrefUtil.getBoolean(this, PrefKey.LOGIN_SET_PAYPWD, false);
            if (!isSetPayPwd) {
                initMsgAlert();
                mMessageAlert.show();
            } else {
                initPasswordAlert();
                mPassworAlert.show();
            }
        }
    }

    @OnTextChanged(value = R.id.withdraw_deposit_money_et, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void moneyTextChanged(Editable s) {
        if (!CommonUtil.isEmpty(s.toString().trim())) {
            double editMoney = Double.parseDouble(s.toString().trim());
            double totalMoney = Double.parseDouble(mTotalMoney);
            if (editMoney > totalMoney) {
                mMoneyEt.setText(mTotalMoney);
                mMoneyEt.setSelection(mTotalMoney.length());
            }
        }
    }

    private boolean checkData() {
        if (mBankCardData == null) {
            showToast("请添加银行卡");
            return false;
        }
        if (CommonUtil.isEmpty(mMoneyEt)) {
            showToast("请输入提现金额");
            return false;
        }
        return true;
    }

    private void paresBankcard() {
        if (mBankCardData != null) {
            mBankcardBindLayout.setVisibility(View.VISIBLE);
            mBankcardNameTv.setText(mBankCardData.getBank());
            mBankcardNoLastTv.setText(mBankCardData.getBankcardNoLast());
        }
    }

    @Override
    public void addListener() {

    }

    @Override
    public void rightListener() {
        Bundle extras = new Bundle();
        extras.putInt(IntentKey.FROM, 1);
        ShowActivity.showActivityForResult(this, MyBankCardActivity.class, extras, RequestCodeKey.GO_GET_BANKCARD);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.GO_GET_BANKCARD:
                    mBankCardData = data.getParcelableExtra(IntentKey.BANK_CARD);
                    paresBankcard();
                    break;
                case RequestCodeKey.GO_DESPOSE:
                    Intent intent = new Intent();
                    intent.putExtra(IntentKey.WITHDRAW_SUCCESS, true);
                    intent.putExtra(IntentKey.TOTAL_MONEY, mTotalMoney);
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
            }
        }
    }

    private void getBankCard() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.getBank(mToken), new BaseObserver(this) {
            @Override
            protected void onHandleSuccess(Object data, String msg) {
                if (data != null) {
                    BankCard bankCard = GsonUtil.parseData(data, BankCard.class);
                    List<BankCard.Data> list = bankCard.getBankList();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).isDefault()) {
                            mBankCardData = list.get(i);
                            break;
                        }
                    }
                    paresBankcard();
                }
            }
        });
    }
}
